<template>
  <div class="container">
    <section>
      <h3>实时生成内容展示</h3>
      <button @click="startSummary" :disabled="isSummaryLoading">
        {{ isSummaryLoading ? '生成中...' : '开始生成' }}
      </button>
      <button @click="abortSummary">中断</button>

      <!-- 🔁 实时显示 -->
      <div class="output-box">
        <pre v-if="summaryData">{{ summaryData }}</pre>
        <div v-else>等待生成内容...</div>
      </div>

      <div v-if="summaryError" style="color: red">{{ summaryError.message }}</div>
    </section>
  </div>
</template>


<script setup lang="ts">
import {ParseFunction, useStreamFetch} from './useStreamFetch'

const difyApi = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions'

// 🔹 请求配置 - 生成会议摘要
const summaryRequestOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer f9c1148b-26fc-4c92-8977-fca871de1af3',
  },
  body: JSON.stringify({
    "model": "deepseek-v3-250324",
    "stream": true,
    "messages": [
      {
        "role": "system",
        "content": "你是一个小说助手."
      },
      {
        "role": "user",
        "content": "你好!"
      }
    ]
  }),
}
const difyParseMessage: ParseFunction = (message: string): string | null => {
  try {
    const parsedData = JSON.parse(message);
    if ('answer' in parsedData) {
      return parsedData.answer;
    }
    return null;
  } catch (e) {
    console.warn('无法解析 Dify 平台的消息内容:', message);
    return null;
  }
};

const volcanoParseMessage: ParseFunction = (message: string): string | null => {
  if (!message.startsWith('data:')) return null;
  const dataStr = message.slice(5).trim();
  try {
    const parsedData = JSON.parse(dataStr);
    if ('choices' in parsedData && parsedData.choices[0].delta.content) {
      return parsedData.choices[0].delta.content;
    }
    return null;
  } catch (e) {
    console.warn('无法解析火山平台的消息内容:', dataStr);
    return null;
  }
};
// 创建 hook 实例
const summaryHook = useStreamFetch(difyApi, summaryRequestOptions,volcanoParseMessage)

// 解构出来用于控制和显示
const {
  data: summaryData,
  isLoading: isSummaryLoading,
  error: summaryError,
  startFetch: startSummary,
  abortFetch: abortSummary,
} = summaryHook
</script>



<style scoped>
.output-box {
  margin-top: 1rem;
  padding: 1rem;
  border: 1px solid #ccc;
  min-height: 100px;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: sans-serif;
  background-color: #f9f9f9;
}
</style>
